package feign.okhttp;

import feign.Client;
import feign.Response;
import feign.Request.Options;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.*;
import java.util.concurrent.TimeUnit;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.Request.Builder;

/**
 * @author chenkh
 * @time 2021/7/13 10:07
 */
public class OkHttpClient implements Client {

    private final okhttp3.OkHttpClient delegate;

    public OkHttpClient() {
        this(new okhttp3.OkHttpClient());
    }

    public OkHttpClient(okhttp3.OkHttpClient delegate) {
        this.delegate = delegate;
    }

    static Request toOkHttpRequest(feign.Request input) {
        Builder requestBuilder = new Builder();
        requestBuilder.url(input.url());
        MediaType mediaType = null;
        boolean hasAcceptHeader = false;
        Iterator var4 = input.headers().keySet().iterator();

        while(var4.hasNext()) {
            String field = (String)var4.next();
            if (field.equalsIgnoreCase("Accept")) {
                hasAcceptHeader = true;
            }

            Iterator var6 = ((Collection)input.headers().get(field)).iterator();

            while(var6.hasNext()) {
                String value = (String)var6.next();
                if (field.equalsIgnoreCase("Content-Type")) {
                    mediaType = MediaType.parse(value);
                    if (input.charset() != null) {
                        mediaType.charset(input.charset());
                    }
                } else {
                    requestBuilder.addHeader(field, value);
                }
            }
        }

        if (!hasAcceptHeader) {
            requestBuilder.addHeader("Accept", "*/*");
        }

        byte[] inputBody = input.body();
        boolean isMethodWithBody = "POST".equals(input.method()) || "PUT".equals(input.method());
        if (isMethodWithBody && inputBody == null) {
            inputBody = new byte[0];
        }

        RequestBody body = inputBody != null ? RequestBody.create(mediaType, inputBody) : null;
        requestBuilder.method(input.method(), body);
        return requestBuilder.build();
    }

    private static Response toFeignResponse(okhttp3.Response input) throws IOException {
        return Response.builder().status(input.code()).reason(input.message()).headers(toMap(input.headers())).body(toBody(input.body())).build();
    }

    private static Map<String, Collection<String>> toMap(Headers headers) {
        Map<String, List<String>> source = headers.toMultimap();
        Map<String, Collection<String>> target = new HashMap<>();
        for (Map.Entry<String,List<String>> entry:source.entrySet()){
            target.put(entry.getKey(),entry.getValue());
        }
        return target;
    }

    private static Response.Body toBody(final ResponseBody input) throws IOException {
        if (input != null && input.contentLength() != 0L) {
            final Integer length = input.contentLength() >= 0L && input.contentLength() <= 2147483647L ? (int)input.contentLength() : null;
            return new Response.Body() {
                public void close() throws IOException {
                    input.close();
                }

                public Integer length() {
                    return length;
                }

                public boolean isRepeatable() {
                    return false;
                }

                public InputStream asInputStream() throws IOException {
                    return input.byteStream();
                }

                public Reader asReader() throws IOException {
                    return input.charStream();
                }
            };
        } else {
            if (input != null) {
                input.close();
            }

            return null;
        }
    }

    public Response execute(feign.Request input, Options options) throws IOException {
        okhttp3.OkHttpClient requestScoped;
        if (this.delegate.connectTimeoutMillis() == options.connectTimeoutMillis() && this.delegate.readTimeoutMillis() == options.readTimeoutMillis()) {
            requestScoped = this.delegate;
        } else {
            requestScoped = this.delegate.newBuilder().connectTimeout((long)options.connectTimeoutMillis(), TimeUnit.MILLISECONDS).readTimeout((long)options.readTimeoutMillis(), TimeUnit.MILLISECONDS).build();
        }

        Request request = toOkHttpRequest(input);
        okhttp3.Response response = requestScoped.newCall(request).execute();
        return toFeignResponse(response).toBuilder().request(input).build();
    }
}
